package org.six11.olive3.picturephone.server.handler;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;

import org.six11.olive3.net.Message;
import org.six11.olive3.net.MessageHandler;
import org.six11.olive3.net.MessageNames;
import org.six11.olive3.net.Message.Param;
import org.six11.olive3.net.Message.Statement;
import org.six11.olive3.net.Message.Value;
import org.six11.olive3.picturephone.server.MessageQueue;
import org.six11.olive3.picturephone.server.PPMessageNames;
import org.six11.olive3.picturephone.server.ServerStateConstants;
import org.six11.olive3.server.DatabaseThing;
import org.six11.olive3.server.SqlStrings;
import org.six11.olive3.util.MultiState;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class ScoreHandler extends MessageHandler {

  private DatabaseThing db;
  private MultiState programState;

  public ScoreHandler(DatabaseThing db, MultiState programState) {
    this.db = db;
    this.programState = programState;
  }

  public void handleLater(Message m) {
    // find the score for the user indicated in the message and put a STATUS message in their queue.
    String uid = m.getParamValue(MessageNames.PARAM_USER_ID);
    enqueueScoreForUser(uid, null);
  }

  @SuppressWarnings("unchecked")
  public void enqueueScoreForUser(String uid, String why) {
    Map<String, MessageQueue> queues = (Map<String, MessageQueue>) programState
        .getValue(ServerStateConstants.MESSAGE_QUEUES);
    if (!queues.containsKey(uid)) {
      return;
    }
    Message messageForUser = new Message(MessageNames.MSG_STATUS);
    Statement scoreStatement = new Statement(MessageNames.STMT_SCORE);
    String scoreVal = getScore(uid);
    scoreStatement.required.add(new Value(scoreVal));
    if (why != null) {
      scoreStatement.optional.add(new Param(PPMessageNames.PARAM_TEXT, why));
    }
    messageForUser.addStatement(scoreStatement);
    queues.get(uid).add(messageForUser);
    bug("added score of " + scoreVal + " for user " + uid + " using optional reason " + why);
  }

  public String getScore(String uid) {
    Map<String, String> row;
    String ret = "0";
    try {
      row = db.getRow(SqlStrings.FIND_SCORE, uid);
      ret = row.get("score");
    } catch (ServletException ex) {
      ex.printStackTrace();
    }
    return ret;
  }

  public void addScore(String uid, String points, String why) {
    String currentScore = getScore(uid);
    int newScoreInt = new Integer(currentScore).intValue() + new Integer(points).intValue();
    String newScore = "" + newScoreInt;
    try {
      bug("Giving user " + uid + " a new score of " + newScore + ", up " + points
          + " from the old score of " + currentScore);
      db.update(SqlStrings.UPDATE_SCORE, newScore, uid);
      enqueueScoreForUser(uid, why);
    } catch (ServletException ex) {
      ex.printStackTrace();
    }
  }

}
